package com.itts.converter;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ConverterFactory implements ApplicationContextAware {
    private static final Map<String, ProposalConverter> map = new ConcurrentHashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ProposalConverter> all = applicationContext.getBeansOfType(ProposalConverter.class);
        for (ProposalConverter converter : all.values()) {
            Class<?>[] aClass = GenericTypeResolver.resolveTypeArguments(converter.getClass(), ProposalConverter.class);
            StringBuilder builder = new StringBuilder();
            for (Class<?> aClass1 : aClass) {
                builder.append(aClass1.getCanonicalName());
            }
            map.put(builder.toString(), converter);
        }
    }
    public static <S,T> ProposalConverter<S ,T> getConverter(Class<S> source, Class<T> target){
        return map.get(source.getCanonicalName() + target.getCanonicalName());
    }
}
